<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>鼠标事件</title>
    <style>
        .outer{
            width: 600px;
            height: 400px;
            margin:100px auto;
            border:solid 1px rgb(34, 2, 2);
            position: relative;
        }

        .inner{
            width: 100px;
            height: 100px;
            background: rgb(169, 125, 184);
            position:absolute;
            left: 0;
            top:0;
        }

        #root .active{
            background: rgb(70, 10, 90)
        }
    </style>
</head>
<body>
    <div id="root"> </div>

    <script src="./js/react.development.js"></script>
    <script src="./js/react-dom.development.js"></script>
    <script src="./js/babel.min.js"></script>

    <script type="text/babel">
        class App extends React.Component{
            render(){
                return <div ref={el => this.outer = el} className="outer">
                        <div  className="inner" 
                            onMouseDown={this.mousedown}  
                            onMouseUp={this.mouseup}
                            onMouseMove={this.mousemove}    

                            onContextMenu={this.contextmenu}
                        ></div>
                    </div>
            }
            
            //鼠标按下事件
            mousedown = (e) => {
                // console.log(e.target);
                e.target.classList.add('active');
                //获取当前鼠标的位置
                this.x = e.clientX;
                this.l = e.target.offsetLeft;

                this.y = e.pageY;
                this.t = e.target.offsetTop;
                //标志鼠标左键已经按下
                this.isDown = true;
            }

            //鼠标抬起事件
            mouseup = (e) => {
                // console.log('鼠标抬起了');
                e.target.classList.remove('active');
                //标识鼠标已经抬起
                this.isDown = false;
            }

            mousemove = (e) => {
                //判断
                if(!this.isDown) return; 

                let newLeft = e.clientX - (this.x - this.l);
                let newTop = e.pageY - (this.y - this.t);
                if(newLeft <= 0) newLeft = 0;
                e.target.style.left = newLeft + 'px';
                e.target.style.top = newTop + 'px';
            }
        
            contextmenu = (e) => {
                // console.log('你右键点击了我');

                //阻止事件的默认行为   return false   e.preventDefault();
                e.preventDefault();
            }
        }

        ReactDOM.render(<App />, document.querySelector("#root"));

    </script>
</body>
</html>